package com.ltu.util.security;


//import Java.security.SecureRandom;
import java.security.*;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import misc.BASE64Encoder;

public class DESUtil2 {
	 private final static String DES = "DESede";
	 
//	 public static void main(String[] args) {		 
//	  try {
//		  String data="啦啦";
//		  String key="12345678";
//	   String jiami = encrypt(data, key);
//	   System.out.print("" + jiami);
//	   byte jiemi[]=decrypt(encrypt(data.getBytes(), key.getBytes()), key.getBytes());
//	    System.err.println("解密: "+new String(jiemi));
//	  } catch (Exception e) {
//	   e.printStackTrace();
//	  }
//	 }
	 /**
	  * 明文输入 密文输出
	  * @param data 数据
	  * @param key 密匙
	  * @return 加密字符串
	  * @throws Exception
	  */
	 public static String encrypt(String data, String key) throws Exception {  //对string进行BASE64Encoder转换
	  byte[] bt = encrypt(data.getBytes("UTF-8"), key.getBytes());
	  String strs =new BASE64Encoder().encode(bt);
	  return strs;
	 }
	 private static byte[] encrypt(byte[] data, byte[] key) throws Exception {  
		//加密代码
	  // 生成一个可信任的随机数源
	  SecureRandom sr = new SecureRandom();
	  // 从原始密钥数据创建DESKeySpec对象
	  DESKeySpec dks = new DESKeySpec(key);
	  // 创建一个密钥工厂，然后用它把DESKeySpec转换成SecretKey对象
	  SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
	  SecretKey securekey = keyFactory.generateSecret(dks);
	  // Cipher对象实际完成加密操作
	  Cipher cipher = Cipher.getInstance(DES);
	  // 用密钥初始化Cipher对象
	  cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);
	  return cipher.doFinal(data);
	 }
	 
	 /**
	  * 密文输入  明文输出 
	  * @param data
	  * @param key
	  * @return
	  * @throws Exception
	  */
	 public static byte[] decrypt(byte[] data, byte[] key) throws Exception {
	  // 生成一个可信任的随机数源
	  SecureRandom sr = new SecureRandom();
	  // 从原始密钥数据创建DESKeySpec对象
	  DESKeySpec dks = new DESKeySpec(key);
	  // 创建一个密钥工厂，然后用它把DESKeySpec转换成SecretKey对象
	  SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
	  SecretKey securekey = keyFactory.generateSecret(dks);
	  // Cipher对象实际完成解密操作
	  Cipher cipher = Cipher.getInstance(DES);
	  // 用密钥初始化Cipher对象
	  cipher.init(Cipher.DECRYPT_MODE, securekey, sr);
	  
	  return cipher.doFinal(data);
	 }
		

}
